package com.imooc.web.intercepter;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Author:   yangdc
 * Date:     2018/9/3 2:15
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("===|===time interceptor preHandler");
        System.out.println("===|===" + ((HandlerMethod) o).getBean().getClass().getName());
        System.out.println("===|===" + ((HandlerMethod) o).getMethod().getName());
        httpServletRequest.setAttribute("startTime", new Date().getTime());

        // true/false是否调用后边的方法 postHandler afterCompletion
        return true;
    }

    // controller抛异常就不会执行这个方法了
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("===|===time interceptor postHandle");
        long start = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("===|===postHandler 耗时:" + (new Date().getTime() - start));
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("===|===time interceptor afterCompletion");
        long start = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("===|===afterCompletion 耗时:" + (new Date().getTime() - start));
        System.out.println("===|===exception:" + e);
    }
}
